import Vue from 'vue'
import VueRouter from 'vue-router'

import { getToken } from '@/utils/storage'

import cc from '@/components/cc'

const Login = () => import('@/views/login')
const Home = () => import('@/(views/layout/home')
const Index = () => import('@/views/layout')
const AddAticle = () => import('@/views/(layout/add-article')
const Articles = () => import('@/(views/layout/articles')
const Comment = () => import('@/(views/layout/comment')
const EditorArticle = () => import('@/views/(layout/articles/editor')
const Fans = () => import('@/(views/layout/fans')
const Pictures = () => import('@/(views/layout/pictures')
const Settings = () => import('@/(views/layout/settings')
const NotFind = () => import('@/views/NotFind')

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  {
    path: '/',
    component: Index,
    meta: {
      name: '首页',
      pathname: '/'
    },
    children: [
      { path: '/', component: Home },
      { path: '/add-article', component: AddAticle },
      {
        path: '/articles',
        component: Articles,
        meta: {
          name: '文章'
        },
        children: [
          {
            path: '/cc',
            component: cc,
            meta: {
              name: '文章cc',
              pathname: '/'
            }
          }
        ]
      },
      { path: '/comment', component: Comment },
      { path: '/editor/:id', component: EditorArticle },
      { path: '/fans', component: Fans },
      { path: '/pictures', component: Pictures },
      { path: '/settings', component: Settings }
    ]
  },
  { path: '*', component: NotFind }

]

const router = new VueRouter({
  routes
})

// 本页体跳本页的错误解决
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return routerPush.call(this, location).catch(error => error)
}

// 导航守卫
router.beforeEach((to, from, next) => {
  // console.log('to', to)
  // console.log('from', from)
  const token = getToken()
  if (token || to.path === '/login') {
    // 如果有token或者去的页面是首页就放行
    next()
  } else {
    next('/login')
  }
})

export default router
